package com.gexiaobao.pigeon.ui.organizer.fragment

import android.graphics.Color
import android.os.Bundle
import androidx.core.view.isVisible
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.viewModels
import cn.qqtheme.framework.picker.OptionPicker
import cn.qqtheme.framework.widget.WheelView
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.ext.initClose
import com.gexiaobao.pigeon.app.ext.showMessage
import com.gexiaobao.pigeon.app.model.bean.FeatherColorResponse
import com.gexiaobao.pigeon.app.model.bean.OrganizerDeviceResponse
import com.gexiaobao.pigeon.app.model.bean.PigeonBean
import com.gexiaobao.pigeon.app.model.param.RingInfoParams
import com.gexiaobao.pigeon.app.model.param.RingSnParams
import com.gexiaobao.pigeon.app.util.KvUtils
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.TransInformation
import com.gexiaobao.pigeon.databinding.FragmentAddPigeonOrgBinding
import com.gexiaobao.pigeon.ui.dialog.DialogPigeonMasterName
import com.gexiaobao.pigeon.viewmodel.MyPigeonViewModel
import com.gexiaobao.pigeon.viewmodel.request.RequestAddPigeonViewModel
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.parseState
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat

/**
 * @Author      : hxw
 * @Date        : 2023/6/1 12:27
 * @Describe    : 组织方-添加赛鸽
 */
class FragmentAddPigeon : BaseFragment<MyPigeonViewModel, FragmentAddPigeonOrgBinding>() {

    private val requestViewModel: RequestAddPigeonViewModel by viewModels()
    private var mSelectedIndex: Int = 0
    private var featherColorId = 0
    private var mPosition = 0
    private var userId = 0
    private var type: Int = 0//1；修改，2：添加
    private var mPigeonId: Int = 0
    private var deviceCode = ""
    private var entryName = ""

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.viewmodel = mViewModel
        userId = requireArguments().getInt("userId")
        type = requireArguments().getInt("type")
        val title = if (type == 1) "修改赛鸽" else "添加赛鸽"
        mDatabind.ivAddPigeonMaster.isVisible = type != 1
        mDatabind.includeBar.toolbar.initClose(title) {
            nav().navigateUp()
        }

        addTextWatch()
        checkedListeners()
    }

    override fun initData() {
        super.initData()
        mDatabind.layoutRingNumber.tvRingNumber.transformationMethod = TransInformation()
        if (type == 1) {
            val data = arguments?.getSerializable("data") as PigeonBean.RingInfo
            if (data != null) {
                mPigeonId = data.pigeonId
//                val colorStr = KvUtils.decodeString(Constant.FEATHER_COLOR_LIST)
                mViewModel.pigeonMasterName.set(data.name)
                mViewModel.pigeonRingSn.set(data.ringSn)

                mViewModel.pigeonFeatherColor.set(data.featherColorStr)

//                if (colorStr.isNotEmpty()) {
//                    val colorList = Gson().fromJson<ArrayList<FeatherColorResponse.ColorList>>(
//                        colorStr,
//                        object : TypeToken<ArrayList<FeatherColorResponse.ColorList>>() {}.type
//                    )
//                    for (index in colorList.indices) {
//                        if (data.featherColor == colorList[index].id) {
//                            mViewModel.pigeonFeatherColor.set(colorList[index].featherColor)
//                        }
//                    }
//                }
                featherColorId = data.featherColor

                if (data.ringId.isNotEmpty()) {
                    val ringId = data.ringId.split("-")
                    if (ringId.isNotEmpty() && ringId.size == 3) {
                        mDatabind.layoutRingNumber.tvRingNumberYear.setText(ringId[0])
                        mDatabind.layoutRingNumber.tvRingNumberArea.setText(ringId[1])
                        mDatabind.layoutRingNumber.tvRingNumber.setText(ringId[2])
                    }
                }
                when (data.sex) {
                    1 -> {
                        mDatabind.rbAddPigeonNo.isChecked = true
                    }

                    2 -> {
                        mDatabind.rbAddPigeonMale.isChecked = true
                    }

                    3 -> {
                        mDatabind.rbAddPigeonFemale.isChecked = true
                    }
                }

                when (data.eyePattern) {
                    1 -> {
                        mDatabind.rbAddPigeonNoColor.isChecked = true
                    }

                    2 -> {
                        mDatabind.rbAddPigeonYellow.isChecked = true
                    }

                    3 -> {
                        mDatabind.rbAddPigeonSha.isChecked = true
                    }

                    4 -> {
                        mDatabind.rbAddPigeonNiu.isChecked = true
                    }
                }
            }
        } else {
            entryName = arguments?.getString("entryName").toString()
            val name = KvUtils.decodeString("fosterName")
            mViewModel.pigeonMasterName.set(name)
        }
    }

    private fun addTextWatch() {
        mDatabind.layoutRingNumber.tvRingNumberYear.addTextChangedListener {
            if (it?.length == 4) {
                mDatabind.layoutRingNumber.tvRingNumberArea.requestFocus()
            }
        }

        mDatabind.layoutRingNumber.tvRingNumberArea.addTextChangedListener {
            if (it?.length == 2) {
                mDatabind.layoutRingNumber.tvRingNumber.requestFocus()
            }
        }
    }

    private fun checkedListeners() {
        mDatabind.rbAddPigeonNo.setOnCheckedChangeListener { _, b ->
            if (b) mViewModel.pigeonSex.set("1")
        }

        mDatabind.rbAddPigeonMale.setOnCheckedChangeListener { _, b ->
            if (b) mViewModel.pigeonSex.set("3")

        }
        mDatabind.rbAddPigeonFemale.setOnCheckedChangeListener { _, b ->
            if (b) mViewModel.pigeonSex.set("2")
        }

        mDatabind.rbAddPigeonNoColor.setOnCheckedChangeListener { _, b ->
            if (b) mViewModel.pigeonEyePattern.set("1")
        }

        mDatabind.rbAddPigeonYellow.setOnCheckedChangeListener { _, b ->
            if (b) mViewModel.pigeonEyePattern.set("2")
        }

        mDatabind.rbAddPigeonSha.setOnCheckedChangeListener { _, b ->
            if (b) mViewModel.pigeonEyePattern.set("3")
        }

        mDatabind.rbAddPigeonNiu.setOnCheckedChangeListener { _, b ->
            if (b) mViewModel.pigeonEyePattern.set("4")
        }
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(
            mDatabind.tvPair,
            mDatabind.tvAddPigeonCommit,
            mDatabind.llFeatherColor,
            mDatabind.ivAddPigeonMaster
        ) {
            when (it) {
                mDatabind.tvPair -> {
                    showLoading(getString(R.string.loading))
                    requestViewModel.getGatherDeviceList()
                }

                mDatabind.ivAddPigeonMaster -> {
                    showPigeonMasterName()
                }

                mDatabind.tvAddPigeonCommit -> {
                    createPigeon()
                }

                mDatabind.llFeatherColor -> {
                    showLoading()
                    requestViewModel.getFeatherColor()
                }
            }
        }
    }

    private fun showPigeonMasterName() {
//        val userName = KvUtils.decodeString(Constant.USER_NAME)
        val dialog = DialogPigeonMasterName(context)
        dialog.setName2(entryName)
        dialog.setName1Listener {
            mViewModel.pigeonMasterName.set(dialog.getName1Text())
            dialog.dismiss()
        }
        dialog.setName2lListener {
            mViewModel.pigeonMasterName.set(dialog.getName2Text())
            dialog.dismiss()
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    private fun toPairRingSn() {
        val body = RingSnParams(deviceCode)
        showLoading(getString(R.string.Acquiring))
        mViewModel.geyRingSn(body)
    }

    private fun createPigeon() {
        when {
            mViewModel.pigeonMasterName.get().isEmpty() -> showMessage("请选择鸽主、寄养人")
            mDatabind.layoutRingNumber.tvRingNumberYear.text!!.isEmpty() || mDatabind.layoutRingNumber.tvRingNumberYear.text!!.length != 4 -> showMessage(
                "填写足环号年份"
            )

            mDatabind.layoutRingNumber.tvRingNumberArea.text!!.isEmpty() || mDatabind.layoutRingNumber.tvRingNumberArea.text!!.length != 2 -> showMessage(
                "填写足环号地区"
            )

            mDatabind.layoutRingNumber.tvRingNumber.text!!.isEmpty() || mDatabind.layoutRingNumber.tvRingNumber.text!!.length != 7 -> showMessage("请填写足环号")
            mViewModel.pigeonRingSn.get().isEmpty() -> showMessage("请选择设备")
            mViewModel.pigeonSex.get().isEmpty() -> showMessage("请选择赛鸽性别")
            mViewModel.pigeonFeatherColor.get().isEmpty() -> showMessage("请选择羽色")
            mViewModel.pigeonEyePattern.get().isEmpty() -> showMessage("请选择眼沙")
            else -> {
                val pigeonRingId =
                    mDatabind.layoutRingNumber.tvRingNumberYear.text.toString() + "-" + mDatabind.layoutRingNumber.tvRingNumberArea.text + "-" + mDatabind.layoutRingNumber.tvRingNumber.text
                showLoading(getString(R.string.loading))
                if (type == 1) {
                    val bean = RingInfoParams(
                        pigeonId = mPigeonId,
                        fosterName = mViewModel.pigeonMasterName.get().trim(),
                        ringId = pigeonRingId,
                        ringSn = mViewModel.pigeonRingSn.get(),
                        sex = mViewModel.pigeonSex.get().toInt(),
                        featherColor = featherColorId,
                        eyePattern = mViewModel.pigeonEyePattern.get().toInt(),
                    )
                    requestViewModel.orgUpdatePigeon(bean)
                } else {
                    val bean = RingInfoParams(
                        userId = userId,
                        fosterName = mViewModel.pigeonMasterName.get().trim(),
                        ringId = pigeonRingId,
                        ringSn = mViewModel.pigeonRingSn.get(),
                        sex = mViewModel.pigeonSex.get().toInt(),
                        featherColor = featherColorId,
                        eyePattern = mViewModel.pigeonEyePattern.get().toInt(),
                    )
                    requestViewModel.createPigeon(bean)
                }
            }
        }
    }

    override fun createObserver() {
        super.createObserver()
        requestViewModel.createPigeon.observe(viewLifecycleOwner) {
            dismissLoading()
            if (it.isSuccess) {
                KvUtils.encode("fosterName", mViewModel.pigeonMasterName.get())
                nav().navigateUp()
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }

        requestViewModel.orgUpdatePigeonResult.observe(viewLifecycleOwner) {
            dismissLoading()
            if (it.isSuccess) {
                nav().navigateUp()
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }

        requestViewModel.deviceResult.observe(viewLifecycleOwner) {
            dismissLoading()
            if (!it.isEmpty()) {
                showDevicePicker(it.info)
            }
        }

        requestViewModel.featherColor.observe(this) {
            dismissLoading()
            if (it.isSuccess) {
                pigeonFeatherColor(it.listData)
            } else {
                RxToast.showToast(it.errMessage)
            }
        }

        mViewModel.ringSn.observe(this) { result ->
            parseState(result, {
                dismissLoading()
                mViewModel.pigeonRingSn.set(it.ringSn)
            })
        }
    }

    private fun pigeonFeatherColor(listData: ArrayList<FeatherColorResponse.ColorList>?) {
        val flyKey: ArrayList<String> = arrayListOf()
        if (listData != null && listData.size != 0) {
            for ((_, item) in listData.withIndex()) {
                flyKey.add(item.featherColor)
            }
        }

        val picker = OptionPicker(activity, flyKey)
        val params = picker.window.attributes
        params.width = activity?.windowManager?.defaultDisplay!!.width
        picker.setCanceledOnTouchOutside(false)
        picker.setDividerRatio(WheelView.DividerConfig.FILL)
        picker.setShadowColor(resources.getColor(R.color.bg_light_bllue), 40)
        picker.selectedIndex = mPosition
        picker.setCycleDisable(true)
        picker.setTitleText("请选择羽色")
        picker.setTitleTextColor(Color.BLACK)
        picker.setTitleTextSize(18)
        picker.setSubmitText("确认")
        picker.setSubmitTextSize(17)
        picker.setSubmitTextColor(resources.getColor(R.color.bg_light_bllue))//确定按钮文字颜色
        picker.setCancelText("取消")
        picker.setCancelTextSize(17)
        picker.setCancelTextColor(resources.getColor(R.color.bg_light_bllue))//取消按钮文字颜色
        picker.setTextSize(18)
        picker.setLineSpaceMultiplier(3.0F)
        picker.setOnOptionPickListener(object : OptionPicker.OnOptionPickListener() {
            override fun onOptionPicked(index: Int, item: String) {
                mViewModel.pigeonFeatherColor.set(item)
                mViewModel.pigeonFeatherColorPosition.set(index + 1)
                mPosition = index
                featherColorId = listData?.get(index)!!.id
            }
        })
        picker.show()
    }

    private fun showDevicePicker(listData: ArrayList<OrganizerDeviceResponse.DataList>) {
        val flyKey: ArrayList<String> = arrayListOf()
        if (listData != null && listData.size != 0) {
            for ((_, item) in listData.withIndex()) {
                flyKey.add(item.imsi)
            }
        }

        val picker = OptionPicker(activity, flyKey)
        val params = picker.window.attributes
        params.width = activity?.windowManager?.defaultDisplay!!.width
        picker.setCanceledOnTouchOutside(false)
        picker.setDividerRatio(WheelView.DividerConfig.FILL)
        picker.setShadowColor(resources.getColor(R.color.bg_light_bllue), 40)
        picker.selectedIndex = mSelectedIndex
        picker.setCycleDisable(true)
        picker.setTitleText("请选择设备")
        picker.setTitleTextColor(Color.BLACK)
        picker.setTitleTextSize(18)
        picker.setSubmitText("确认")
        picker.setSubmitTextSize(17)
        picker.setSubmitTextColor(resources.getColor(R.color.bg_light_bllue))//确定按钮文字颜色
        picker.setCancelText("取消")
        picker.setCancelTextSize(17)
        picker.setCancelTextColor(resources.getColor(R.color.bg_light_bllue))//取消按钮文字颜色
        picker.setTextSize(18)
        picker.setLineSpaceMultiplier(3.0F)
        picker.setOnOptionPickListener(object : OptionPicker.OnOptionPickListener() {
            override fun onOptionPicked(index: Int, item: String) {
                mSelectedIndex = index
                deviceCode = item
                toPairRingSn()
            }
        })
        picker.show()
    }
}